#!/bin/bash
#description: install memcached on centos7
#date 2018/02/21
#
MEMCACHED_VERSION=1.5.5
SOFTDIR=/usr/local/src
#install libevent
cd /usr/local/src
[ ! -f libevent-2.1.8-stable.tar.gz ] && wget  http://soft.51yuki.cn/libevent-2.1.8-stable.tar.gz
[ ! -d libevent-2.1.8-stable ] && tar xf libevent-2.1.8-stable.tar.gz && cd libevent-2.1.8-stable && ./configure --prefix=/usr/libevent && make && make install 
/usr/sbin/ldconfig
#install memcached
cd /usr/local/src && [ ! -f memcached-${MEMCACHED_VERSION}.tar.gz ] && wget http://www.memcached.org/files/memcached-${MEMCACHED_VERSION}.tar.gz 
[ ! -d memcached-${MEMCACHED_VERSION} ] && tar xf memcached-${MEMCACHED_VERSION}.tar.gz && cd memcached-${MEMCACHED_VERSION} && ./configure -with-libevent=/usr/libevent/ -prefix=/usr/local/memcached && make && make install
#configure memcached
cat > /etc/sysconfig/memcached <<EOF
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="256"
OPTIONS=""
EOF
#add memcached user
if ! id memcached &>/dev/null ;then
	groupadd -g 1120 memcached
	useradd -u 1120 -g memcached -s /sbin/nologin memcached
fi
#add memcached start scripts
cd /usr/lib/systemd/system
USER="memcached"
PORT="11211"
CACHESIZE="256"
MAXCONN="1024"
OPTIONS=""
IPADDR="192.168.20.133"
cat > memcached.service <<EOF
[Unit]
Description=Memcached
Before=httpd.service
After=network.target

[Service]
Type=simple
EnvironmentFile=-/etc/sysconfig/memcached
ExecStart=/usr/local/memcached/bin/memcached -u $USER -p $PORT -m $CACHESIZE -c $MAXCONN -l $IPADDR $OPTIONS

[Install]
WantedBy=multi-user.target
EOF

#start memcached 
systemctl restart memcached.service  
if [ "`ps -ef|grep memcached|wc -l`" -gt 1 ] ;then
	echo "memcached start successful"
else
	echo "memcached start fail"
fi
